package org.yan.kangaroo.auth.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.yan.kangaroo.auth.service.email.EmailSendService;
import org.yan.kangaroo.captcha.CaptchaUtils;
import org.yan.kangaroo.common.response.Result;
import org.yan.kangaroo.common.util.McpStringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author wangx
 * @date 11/11/2019 14:44
 */
@RestController
@RequestMapping("/api/v1/captcha")
@AllArgsConstructor
@Slf4j
public class CaptchaController {

    private final StringRedisTemplate redisTemplate;

    private final EmailSendService emailSendService;


    @GetMapping(value = "/email/generate")
    public Result<String> getEmailVerifyCode(@RequestParam("email") String email) {
        String captchaId = McpStringUtils.getUuid();
        String verifyCode = CaptchaUtils.randomCode();
        emailSendService.sendLoginVerifyCode(email, verifyCode);
        redisTemplate.opsForValue().set(captchaId, verifyCode, 5L, TimeUnit.MINUTES);
        return Result.ok(captchaId);
    }

    @GetMapping("/init")
    public Result<String> generateCaptcha() {
        String captchaId = McpStringUtils.getUuid();
        String verifyCode = CaptchaUtils.randomCode();
        redisTemplate.opsForValue().set(captchaId, verifyCode, 5L, TimeUnit.MINUTES);
        return Result.ok(captchaId);
    }

    @GetMapping("/draw/{captchaId}")
    public void viewCaptcha(@PathVariable("captchaId") String captchaId, HttpServletResponse response) throws IOException {
        String verifyCode = redisTemplate.opsForValue().get(captchaId);
        BufferedImage bufferedImage = CaptchaUtils.generateCaptcha(verifyCode);
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        ImageIO.write(bufferedImage, "PNG", response.getOutputStream());
    }


}
